import AMap from 'AMap';
import AMapUI from 'AMapUI';
//定位
export const geolocation = () => {
    return new Promise((resolve,reject) => {
        AMap.plugin('AMap.Geolocation', function() {
            var geolocation = new AMap.Geolocation({
              // 是否使用高精度定位，默认：true
              enableHighAccuracy: true,
              // 设置定位超时时间，默认：无穷大
              timeout: 10000,
              // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
              buttonOffset: new AMap.Pixel(10, 20),
              //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
              zoomToAccuracy: true,     
              //  定位按钮的排放位置,  RB表示右下
              buttonPosition: 'RB'
            })
          
            geolocation.getCurrentPosition()
            AMap.event.addListener(geolocation, 'complete', onComplete)
            AMap.event.addListener(geolocation, 'error', onError)
          
            function onComplete (data) {
              // data是具体的定位信息
              resolve(data)
            }
          
            function onError (data) {
              // 定位出错
              reject(data)
            }
          })
    })
}

//搜索

export const autocomplete = (keyword) => {
    return new Promise((resolve,reject) => {
        AMap.plugin(['AMap.Autocomplete'], function(){
            // 实例化Autocomplete
            var autoOptions = {
                //city 限定城市，默认全国
                city: '全国'
            }
            var autoComplete= new AMap.Autocomplete(autoOptions);
            autoComplete.search(keyword, function(status, result) {
                if(status === 'complete'){
                    resolve(result);
                }else{
                    reject(result)
                }
                // 搜索成功时，result即是对应的匹配数据
            })
        })
    })
}

//选址

export const positionPicker = () => {
    return new Promise((resolve,reject) => {
        AMapUI.loadUI(['misc/PositionPicker'], function(PositionPicker) {
            var map = new AMap.Map('container',{
                zoom:16
            })
            var positionPicker = new PositionPicker({
                mode:'dragMap',//设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
                map:map//依赖地图对象
            });
            //TODO:事件绑定、结果处理等
            positionPicker.on('success', function(positionResult) {
                console.log(positionResult);
                resolve(positionResult)
            });
            positionPicker.on('fail', function(positionResult) {
                console.log(positionResult);
                reject(positionResult)
            });
            positionPicker.start();
        });
    })
}